package com.learning.mediacomponent.service;

import static com.learning.mediacomponent.RecordActivity.uri_list;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import android.net.Uri;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.provider.AlarmClock;
import android.util.Log;

import com.learning.mediacomponent.MainActivity;
import com.learning.mediacomponent.R;
import com.learning.mediacomponent.RecordActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class RecordingService extends Service {
    private static final String CHANNEL_ID = "RecordingServiceChannel";
    private MediaRecorder recorder;
    private String outputFile;
    private long pauseTime = 0;
    private NotificationManager notificationManager;
    private long startTime = 0;          // 录音开始时间
    private long totalPauseTime = 0;    // 总暂停时长
    private long pauseStartTime = 0;    // 当前暂停开始时间
    private boolean isRecording = false;
    private boolean isPaused = false;

    private TelephonyManager telephonyManager;
    private PhoneStateListener phoneStateListener;
    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 返回 Binder 实例，供绑定的组件使用
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
//        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        phoneStateListener = new PhoneStateListener() {
//            @Override
//            public void onCallStateChanged(int state, String phoneNumber) {
//                super.onCallStateChanged(state, phoneNumber);
//                if (state == TelephonyManager.CALL_STATE_RINGING || state == TelephonyManager.CALL_STATE_OFFHOOK) {
//                    // 暂停录音
//                    pauseRecording();
//                }
//            }
//        };
//        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);




    }

    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action = intent.getAction();
        if (action != null) {
            switch (action) {
                case "START":
                    outputFile = intent.getStringExtra("outputFile");
                    startRecording();
                    break;
                case "PAUSE":
                    pauseRecording();
                    break;
                case "RESUME":
                    resumeRecording();
                    break;
                case "SAVE":
                    saveRecording(intent.getStringExtra("fileName"));
                    stopSelf();
                    break;
                case "CANCEL":
                    cancelRecording();
                    stopSelf();
                    break;
            }
        }

//        // 创建并显示通知
//        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
//                .setContentTitle("录音中")
//                .setContentText("录音正在进行中...")
//                .setSmallIcon(R.drawable.ic_microphone)
//                .setOngoing(true)
//                .build();
//
//        startForeground(1, notification);


        return START_STICKY;
    }

    private void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(outputFile);

        try {
            recorder.prepare();
            recorder.start();
            startTime = System.currentTimeMillis(); // 开始时间
            isRecording = true;
            isPaused = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void pauseRecording() {
        if (recorder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            recorder.pause();
            isPaused = true;
            pauseStartTime = System.currentTimeMillis();
        }
    }

    private void resumeRecording() {
        if (recorder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isPaused) {
            recorder.resume();
            isPaused = false;
            totalPauseTime += System.currentTimeMillis() - pauseStartTime;
        }
    }

    private void saveRecording(String fileName) {
        if (recorder != null) {
            recorder.stop();
            recorder.release();
            recorder = null;

            saveToMediaStore(fileName);
        }
    }

    private void cancelRecording() {
        if (recorder != null) {
            recorder.stop();
            recorder.release();
            recorder = null;

            // 删除临时文件
            File tempFile = new File(outputFile);
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    private void saveToMediaStore(String fileName) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.DISPLAY_NAME, fileName + ".wav");
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/wav");

        ContentResolver resolver = getContentResolver();
        Uri collection;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
            collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        } else {
            collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        if (collection == null) {
            Log.e("123456", "Collection URI is null");
            return; // 防止继续执行
        }

        Uri newUri = resolver.insert(collection, values);


        try {
            if (newUri != null) {
                String savedFilePath = newUri.toString();
                Log.i("123456", "saveToMediaStore: " + savedFilePath);
                uri_list.add(savedFilePath);
                File tempFile = new File(outputFile);
                try (FileInputStream fis = new FileInputStream(tempFile);
                     FileOutputStream fos = new FileOutputStream(resolver.openFileDescriptor(newUri, "w").getFileDescriptor())) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        fos.write(buffer, 0, length);
                    }
                }
                tempFile.delete();  // 删除临时文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Recording Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (recorder != null) {
            recorder.release();
        }

    }
}
